package connet_sever;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class ConnectServer {
	private static final int PORT = 2000;
	private static final String URL = "127.0.0.1";
	
	
	private Socket socket;
	private ObjectOutputStream output;
	private ObjectInputStream input;
	
	public static ConnectServer instance = null;
	
	private ConnectServer()
	{
		try{
			socket = new Socket(URL,PORT);
			output = new ObjectOutputStream(socket.getOutputStream());
			output.writeInt(0);
			output.flush();
		}catch(UnknownHostException e)
		{
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
 
		
	}
	
	public Object recieve()
	{
		
		Object obj = null;
		try {
			input = new ObjectInputStream(socket.getInputStream());
			obj = input.readObject();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return obj;
	}
	
	public boolean send(int cmd,Object obj) throws IOException
	{
		output = new ObjectOutputStream(socket.getOutputStream());
		output.writeInt(cmd);
		
		output.writeObject(obj);
		output.flush();
		return socket.isConnected();
	}
	
	public void close()
	{
		try{
			input.close();
			output.close();
			socket.close();
			instance = null;
		}catch(IOException e){
			e.printStackTrace();
		}
	}
	
	public static ConnectServer create_instance()
	{
		if(instance == null)
			return new ConnectServer();
		else return instance;
	}
}

